package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.AddressInfoForm;
import com.springboot.cloud.demos.entity.param.AddressInfoQueryParam;
import com.springboot.cloud.demos.entity.po.AddressInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class AddressInfoService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "conditionsFallback")
    public Result conditions(@RequestBody AddressInfoQueryParam param) {
        return restTemplate.postForEntity("http://producer/addressInfo/conditions", param, Result.class).getBody();
    }

    public Result conditionsFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "addressInfoFallback")
    public Result addressInfo(String id) {
        return restTemplate.getForEntity("http://producer/addressInfo/{id}", Result.class, id).getBody();
    }

    @SentinelResource(fallback = "addressInfoFallback")
    public void delete(String id) {
        restTemplate.delete("http://producer/addressInfo/{id}", id);
    }

    public Result addressInfoFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody AddressInfoForm addressInfoForm) {
        return restTemplate.postForEntity("http://producer/addressInfo", addressInfoForm, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody AddressInfoForm addressInfoForm) {
        restTemplate.put("http://producer/addressInfo/{1}", addressInfoForm, addressInfoForm.getId());
        return Result.success();
    }

    public Result saveFallback(@RequestBody AddressInfoForm addressInfoForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result updateFallback(AddressInfo addressInfo) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }
}
